<template>
  <div class="role-base-wrapper">
    <!-- 主要部分 -->
    <main class="user_main_part">
      <!-- 💭筛选框 -->
      <section class="users_input">
        <el-form
          ref="formRef"
          :model="formData"
          label-width="150px"
          style="width: 90%; margin: 0 auto; text-align: center"
        >
          <el-row type="flex" align="middle">
            <el-col v-for="item in formColumns" :key="item.prop" :span="8">
              <el-form-item :label="item.label" :prop="item.prop">
                <!-- 输入框 -->
                <el-input
                  v-if="item.ele === 'input'"
                  v-model="formData[item.prop]"
                  placeholder="请输入"
                  style="width: 100%"
                  maxlength="30"
                  size="mini"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- 按钮 -->
            <el-col :span="8">
              <el-button type="primary" size="mini" @click="btnSearch">查询</el-button>
              <el-button size="mini" @click="btnClear">重置</el-button>
              <el-button type="primary" size="mini" @click="handleCopyEditAdd({}, 'add')">新增</el-button>
            </el-col>
          </el-row>
        </el-form>
      </section>
      <!-- 💭表格部分 -->
      <section class="users_table">
        <!-- 表格 -->
        <el-table :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :data="tableData" :stripe="true">
          <el-table-column label="角色名称" align="center" prop="name"> </el-table-column>
          <el-table-column label="角色代码" align="center" prop="code"> </el-table-column>
          <!-- <el-table-column label="角色类型" align="center" prop="type"> </el-table-column> -->
          <el-table-column label="状态" align="center" prop="status">
            <template v-slot="{ row }">
              <el-tag v-if="row.status === 0" type="success">激活</el-tag>
              <el-tag v-if="row.status === 1" type="danger">停用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="描述" align="center" prop="remark"> </el-table-column>
          <el-table-column label="操作" align="center" width="180px">
            <template v-slot="{ row }">
              <el-button type="text" @click="handleCopyEditAdd(row, 'copy')">复制</el-button>
              <el-button type="text" @click="handleCopyEditAdd(row, 'edit')">修改</el-button>
              <el-button type="text" @click="btnDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="end" style="height: 60px" align="middle">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageParams.pageNo"
            :page-sizes="[10, 20, 50]"
            :page-size="pageParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </section>
      <!-- 弹窗 -->
      <RoleEditDia
        :editVis.sync="editVis"
        :diaType="diaType"
        :editData="editData"
        :selectedMenus="selectedMenus"
        @createRoleData="createRoleData"
        @updateRoleData="updateRoleData"
      ></RoleEditDia>
    </main>
  </div>
</template>
<script>
import RoleEditDia from './components/RoleEditDia.vue'
import { mapActions } from 'vuex'
// import { flattenDeep } from 'lodash-es'

export default {
  name: 'role-manage',
  components: {
    RoleEditDia,
  },
  data() {
    return {
      formColumns: [{ ele: 'input', label: '角色名称：', prop: 'name' }],
      formData: {
        name: '',
      },
      tableData: [],
      editVis: false,
      diaType: '',
      editData: {},
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      projectId: '',
      selectedMenuIds: [],
      selectedMenus: [],
    }
  },
  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.getTableData()
  },
  methods: {
    ...mapActions('roleManage', [
      'createRoleDataAPI', // 增加projectId
      'getRoleDataAPI', // 增加projectId
      'updateRoleDataAPI',
      'deleteRoleDataAPI',
      'getListByRolerAPI',
    ]),

    async handleCopyEditAdd(row, string) {
      if (string === 'add') {
        this.editData = {}
      } else {
        // 获取当前角色的菜单
        const params = { roleId: row.id }
        const res = await this.getListByRolerAPI({
          params,
        })
        let menuIds = []
        if (res.code === 200) {
          this.selectedMenuIds = []
          this.selectedMenus = []
          menuIds = this.formateMenuIds(res.data)
        }

        this.editData = { ...row }
        this.editData.menuIds = menuIds
      }
      this.diaType = string
      this.editVis = true
    },

    // 整理节点
    formateMenuIds(menuIds) {
      menuIds.map((mItem, mIndex) => {
        this.selectedMenuIds.push(mItem.id)
        this.selectedMenus.push(mItem)
        if (mItem.children && mItem.children.length > 0) {
          this.formateMenuIds(mItem.children)
        }
      })
      return this.selectedMenuIds
    },

    btnDelete(row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 用户点击了确定按钮，执行相应的操作
          const params = {
            id: row.id,
          }
          this.deleteRoleDataAPI({ params }).then(res => {
            const { code } = res
            if (code === 200) {
              this.$message.success('删除成功')
              this.pageParams.pageNo = 1
              this.getTableData()
            }
          })
        })
        .catch(() => {})
    },
    btnSearch() {
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.getTableData()
    },

    getTableData() {
      const params = {
        ...this.formData,
        ...this.pageParams,
        projectId: this.projectId,
      }
      this.getRoleDataAPI({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.total = data.total
          this.tableData = data.records
        }
      })
    },
    btnClear() {
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.$refs.formRef.resetFields()
      this.getTableData()
    },

    // 创建
    createRoleData(payload) {
      const data = {
        ...payload,
        projectId: this.projectId,
      }
      this.createRoleDataAPI({ data }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message.success('新增成功')
          // 重新获取数据
          this.getTableData()
        }
      })
    },
    // 修改
    async updateRoleData(payload) {
      const data = {
        ...payload,
      }
      // 修改用户信息
      await this.updateRoleDataAPI({ data }).then(res => {
        const { code } = res
        if (code === 200) {
          this.$message.success('修改成功')
        }
      })
      // 重新获取数据
      this.getTableData()
    },

    // 分页size change事件
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.getTableData()
    },

    // 分页current change事件
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getTableData()
    },
  },
}
</script>
<style lang="scss" scoped>
.role-base-wrapper {
  background-color: $white;
  height: 100%;
  .user_main_part {
    background-color: $white;
    padding: 12px;
    .users_input {
      margin-top: 12px;
      .el-form-item {
        margin: 0;
      }
    }
    .users_table {
      margin-top: 24px;
    }
  }
}
</style>
